/**
 * Get signature and policy, for authorization.
 * @description policy and signature from your backend method ObsClient.createPostSignature
 * @returns Promise, including authorization data
 */
export async function getAuthorization() {
    return axios.get('/api-xxx')
        .then((res) => {
            if (res.status < 300 && res.data?.code == 200) {
                console.log('Authorization data:', res.data?.data)
                return  res.data?.data || {}
            }
            else {
                return Promise.reject(res)
            }
        })
        .catch(error => {
            console('Get authorization failed', error)
        })
}

/**
 * Upload file
 * @param {*} formData FormData with file, policy and signature.
 * @param {*} options.obsBucketName OBS bucket name
 * @param {*} options.endpoint OBS endpoint for your zone
 * @returns Promsie
 */
export async function upload(formData, {
    obsBucketName, endpoint
}) {
    const baseURL = getUploadURL(obsBucketName, endpoint)
    return axios.post('/', formData, {
        baseURL,
        ContentType: 'multipart/form-data',
    })
}

/**
 * Splicing bucket name and endpoint together, eg: "http://bucketname.your-endpoint/"
 * @param {*} obsBucketName OBS bucket name
 * @param {*} endPoint OBS endpoint for your zone
 * @returns upload request url
 */
export function getUploadURL(obsBucketName, endpoint) {
    let url = endpoint
    url = url.replace(/(https?:\/\/)/g, '$1' + obsBucketName + '.')
    console.log('baseURL:', url)
    return url
}

/**
 * submit handler
 * @param {*} file
 * @param {*} options.filename
 * @param {*} options.ak 
 * @param {*} options.endpoint
 * @param {*} options.xObsAcl
 * @param {*} options.contentType
 */
export function buildFormData(file, {
    filename,
    ak,
    authorizationData,
    xObsAcl,
    contentType,
}) {
    let formData = new FormData()

    // Change form items order may get problem.
    formData.append('key', filename)
    formData.append('x-obs-acl', xObsAcl) // set same value as your backend
    formData.append('content-type', contentType) // set same value as your backend
    formData.append('policy', authorizationData.policy)
    formData.append('AccessKeyId', ak)
    formData.append('signature', authorizationData.signature)
    formData.append('file', file)

    return formData
}
